import pymysql
from pymysql import Connection

def init():
    myconnect = pymysql.Connect(  # 连接数据库
        host='localhost',
        port=3306,
        user='root',
        passwd='',
        db='taobao',
        charset='utf8'
    )
    mycursor = myconnect.cursor()  # 获取游标
    
    return myconnect, mycursor

def delt(myconnect, mycursor):
	
    mycursor.close()
    myconnect.close()

def insert_data(myconnect, mycursor):
    try:
        sql = " insert into user(uname, upassword) values('ma6','mayun');"  # 插入数据
        mycursor.execute(sql)
    except Exception as e:
        print('增出现异常')
        myconnect.rollback()
    else :
        myconnect.commit()

def delete_data(myconnect, mycursorh, uid):
    try:
        sql = " delete from user WHERE uid = {uu};".format(uu = uid)  # 删除数据
        mycursor.execute(sql)
    except Exception as e:
        print('删出现异常')
        myconnect.rollback()
    else:
        myconnect.commit()
    
def update_data(myconnect, mycursor, uid, upwd):
    try:
        sql = "update user set upassword='{pp}' WHERE uid = {uu};".format(
	        uu = uid,
            pp = upwd
        )
        mycursor.execute(sql)
    except Exception as e:
        print('出现异常')
        myconnect.rollback()
    else:
        myconnect.commit()

def select_data(myconnect, mycursor):
    try:
        sql = " select *  from user"  # 查询数据
        mycursor.execute(sql)
        for data in mycursor.fetchall():
            print(data)
    except Exception as e:
        print('出现异常')


if __name__ == '__main__':
    myconnect , mycursor = init()
    
    # insert_data(myconnect, mycursor )
    
    # delete_data(myconnect, mycursor, 8)
    
    # update_data(myconnect, mycursor, 9, "123123")

    select_data(myconnect, mycursor)
    
    delt(myconnect, mycursor)
